<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use StudyBuddy\Responder;

/**
 * This controller processes the "Select Tumblr blog" form
 * where user selects one Tumbl blog to be
 * the default blog connected to the user account.
 * 
 * That "Select" form appear only during "Connect Tumblr"
 * process (in a popup window) and only if it's detected
 * that user has more than one blog on Tumblr
 *
 */
class Tumblrselect extends WebPage
{

	protected $requireToken = true;

	protected $bRequirePost = true;

	protected $bInitPageDoc = false;

	protected $JS = '
		var myclose = function(){
		window.close();
		}
		if(window.opener){
		setTimeout(myclose, 300); // give opener window time to process login and cancell intervals
		}else{
			alert("This is not a popup window or opener window gone away");
		}';



	protected function main(){
		$a = $this->oRegistry->Viewer->getTumblrBlogs();
		d('$a: '.print_r($a, 1));

		if(empty($a)){
			throw new \Exception('No blogs found for this user');
		}

		$selectedID = (int)substr($this->oRequest->get('blog'), 4);
		d('$selectedID: '. $selectedID);

		/**
		 * Pull the selected blog from array of user blogs
		 *
		 * @var unknown_type
		 */
		$aBlog = \array_splice($a, $selectedID, 1);
		d('$aBlog: '.print_r($aBlog, 1));
		d('a now: '.print_r($a, 1));

		/**
		 * Now stick this blog to the
		 * beginning of array. It will become
		 * the first element, pushing other blogs
		 * down in the array
		 * User's "Connected" blog is always
		 * the first blog in array!
		 *
		 */
		\array_unshift($a, $aBlog[0]);
		d('a after unshift: '.print_r($a, 1));

		$this->oRegistry->Viewer->setTumblrBlogs($a);
		/**
		 * Set b_tm to true which will result
		 * in "Post to Tumblr" checkbox to
		 * be checked. User can uncheck in later
		 */
		$this->oRegistry->Viewer['b_tm'] = true;
		$this->oRegistry->Viewer->save();

		$s = Responder::PAGE_OPEN. Responder::JS_OPEN.
		$this->JS.
		Responder::JS_CLOSE.
		'<div id="tools"><h2>You have successfully connected your Tumblr Blog. You should close this window now</h2><br>
		<input type="button"  class="btn-m" onClick="window.close();" value="&nbsp;Close&nbsp;"></div>'.
		Responder::PAGE_CLOSE;
		d('cp s: '.$s);
		echo $s;
		fastcgi_finish_request();
		exit;
	}

}
